﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Expression.Encoder.Devices;
using Microsoft.Expression.Encoder.Live;

// ReSharper disable CheckNamespace
namespace Webcam
// ReSharper restore CheckNamespace
{
    public partial class Form1 : Form
    {
        public EncoderDevice audio;
        public EncoderDevice video;
        List<EncoderDevice> videos = new List<EncoderDevice>();
        List<EncoderDevice> audios = new List<EncoderDevice>(); 

        public Form1()
        {
            InitializeComponent();
            EnumerateDevices();
        }

        private void EnumerateDevices()
        {
            foreach (EncoderDevice ecd in EncoderDevices.FindDevices(EncoderDeviceType.Video))
            {
                 
                lbVideoDevices.Items.Add(ecd.Name);
                videos.Add(ecd);
            }
            foreach (EncoderDevice ecd in EncoderDevices.FindDevices(EncoderDeviceType.Audio))
            {
                lbAudioDevices.Items.Add(ecd.Name);
                audios.Add(ecd);
            }

            lbVideoDevices.DisplayMember = "Name";
            lbAudioDevices.DisplayMember = "Name";
        }


        public void firstVideoDevices_SelectedValueChanged(object sender, EventArgs e)
        {
            foreach (EncoderDevice ecd in videos)
            {
                if (ecd.Name == lbVideoDevices.Text)
                {
                    video = ecd;
                }
            }
        }

        public void firstAudioDevices_SelectedValueChanged(object sender, EventArgs e)
        {
            foreach (EncoderDevice ecd in audios)
            {
                if (ecd.Name == lbAudioDevices.Text)
                {
                    audio = ecd;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var job = new Microsoft.Expression.Encoder.Live.LiveJob();
            var devicesource = job.AddDeviceSource(video, audio);
            devicesource.PreviewWindow = new PreviewWindow(new HandleRef(eh1, eh1.Handle));
            job.ActivateSource(devicesource);
            job.StartEncoding();
            
        }
    }
}